<template>
    <div>
        <navigation-bar :customTitle="curTitle">
            <div class="searchContent">
                下发时间：
                <DatePicker type="daterange" v-model="selectedDate" @change="changeDate" placeholder="日期范围" style="width: 210px" />
                配发方案：
                <el-select
                    v-model="optionValue"
                    placeholder="请选择配发方案"
                    style="width: 200px"
                    @change="
                        (e) => {
                            selectChange(e)
                        }
                    "
                >
                    <el-option
                        :label="select.label"
                        :value="select.value.toString()"
                        v-for="(select, sIndex) in options"
                        :key="sIndex"
                    ></el-option>
                </el-select>
                <el-input
                    v-model="userName"
                    placeholder="请输入账户信息，支持模糊查找"
                    size="mini"
                    style="width: 200px; margin-right: 10px; margin-left: 10px"
                ></el-input>
                <custom-button type="search" style="margin-right: 10px" @searchClick="searchClick"></custom-button>
                <custom-button type="reset" @resetClick="resetClick"></custom-button>
            </div>
        </navigation-bar>

        <div>
            <table-index
                :dataSource="dataSource"
                :tableColumns="tableColumns"
                :btnList="btnList"
                :pageSize="pageSize"
                :pageCount="pageCount"
                :pageNo="pageNo"
                @pageChange="pageChange"
                @viewRow="viewRow"
                @editRow="editRow"
                @deleteRow="deleteRow"
                selection
                @handleSelectionChange="handleSelectionChange"
                :height="secondTableHeight"
            ></table-index>
            <Spin size="large" fix v-if="spinShow" class="demo-spin">
                <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
                <div>数据加载中...</div>
            </Spin>
        </div>

        <add-air-plan v-if="showAdd" @dialogClose="showAdd = false" :type="type" @getData="getData"></add-air-plan>
    </div>
</template>

<script>
import {userManageForm} from '@/assets/form/managementCenter/systemManage/userManage'
import {resetPwdForm} from '@/assets/form/managementCenter/systemManage/resetPwd'
import customDialog from '@/components/customComponents/customDialog'
import customButton from '@/components/customComponents/customForm/customButton'
import formIndex from '@/components/customComponents/customForm/formIndex'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import navigationBar from '@/components/customComponents/managementCenter/navigationBarCustomTitle'
import {AjaxCommon, AjaxCommonExcelDownload} from '@/libs/apiCommon'
import {CardId} from '@/libs/cardId'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
import addAirPlan from './addAirPlan.vue'
export default {
    components: {
        navigationBar,
        customButton,
        tableIndex,
        customDialog,
        formIndex,
        addAirPlan
    },
    props: ['treeNode'],
    watch: {
        treeNode: {
            handler(newV, oldV) {
                const isTrue = Utility.isEqual(newV, oldV)
                if (newV && oldV && !isTrue) {
                    this.treeList = newV
                    this.initPage(newV)
                }
            },
            immediate: true
        }
    },
    data() {
        return {
            optionValue: 'name',
            options: [
                {
                    value: 'name',
                    label: '方案1'
                },
                {
                    value: 'realname',
                    label: '方案2'
                }
            ],
            selectedDate: null,
            showAdd: false,
            spinShow: false,
            treeList: [],
            dde: 0,
            sde: 0,
            // 操作类型（ 0核销 1下发）
            oprType: '0',

            orgInfo: {},
            secondTableHeight: 80,
            selectUserList: [],
            userName: null,
            status: '',
            curTitle: '定额下发结果查询',
            statusList: Utility.getDictList('status'),
            // table 相关参数  begin
            dataSource: [],
            tableColumns: [
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    key: 'famc',
                    title: '方案名称',
                    width: 140,
                    align: 'center'
                },
                {
                    key: 'czsj',
                    title: '发放时间',
                    width: 180
                },
                {
                    key: 'zhczr',
                    title: '发放人',
                    width: 110
                },
                {
                    key: 'dongji',
                    title: '成功账户数',
                    width: 130,
                    align: 'center'
                },
                {
                    key: 'dongji',
                    title: '失败账户数',
                    width: 130,
                    align: 'center'
                },
                {
                    key: 'dongji',
                    title: '单个账户发放金额（元）',
                    width: 200,
                    align: 'center'
                },
                {
                    key: 'dongji',
                    title: '总发放金额（元）',
                    width: 180,
                    align: 'center'
                },

                {
                    key: 'bz',
                    title: '备注',
                    // width: 203
                    fixed: 'right'
                }
            ],
            btnList: ['edit', 'delete'],
            pageSize: 20,
            pageCount: 100,
            pageNo: 1,
            // table 相关参数  end

            // 弹窗是否显示
            dialogShow: false,
            // 弹窗标题 (新增修改不同)
            dialogTitle: '',

            // form的配置信息
            formConfig: null,
            type: 'add',

            formResetConfig: resetPwdForm(''),
            acGuid: ''
        }
    },
    created() {
        this.formConfig = userManageForm('add')
    },
    methods: {
        getData(d) {
            this.showAdd = false
        },
        exportXls() {
            let title = '定额管理'
            const treeList = this.treeList
            if (treeList.length == 0) {
                PopupCommon.notify('info', '请勾选左侧建筑树')
                return
            }
            const id = treeList.map((t) => t.id).toString()
            let params = `/api/QuotaAllot/ExportProducts?buildIds=${id}`
            if (this.userName) {
                params += `&ac_name=${this.userName}`
            }
            AjaxCommonExcelDownload(params).then(
                (response) => {
                    const blob = new Blob([response.data], {
                        type: 'application/vnd.ms-excel'
                    })
                    const link = document.createElement('a')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = title + '.xls'
                    link.click()
                },
                (error) => {
                    console.log(error.message)
                }
            )
            // AjaxCommon(params, 'get', null).then(
            //     (response) => {
            //         const blob = new Blob([response.data], {
            //             type: 'application/vnd.ms-excel'
            //         })
            //         const link = document.createElement('a')
            //         link.href = window.URL.createObjectURL(blob)
            //         link.download = title + '.xls'
            //         link.click()
            //     },
            //     (error) => {
            //         console.log(error.message)
            //     }
            // )
        },
        changeMoeny(e) {
            if (e > 10000) {
                this.dde = 10000
            }
            if (e < 0) {
                this.dde = 0
            }
        },
        changeMoeny1(e) {
            if (e > 10000) {
                this.sde = 10000
            }
            if (e < 0) {
                this.sde = 0
            }
        },
        importClick() {
            this.resetClick()
        },
        getHeight() {
            // 1825
            this.secondTableHeight = document.getElementsByClassName('rightContentHref')[0].clientHeight - 85
        },
        handleSelectionChange(d) {
            this.selectUserList = d
        },
        formInputChange(e) {
            if (e.filedName == 'idCard') {
                const data = CardId.getInfoByCardId(e.value)
                if (data) {
                    let newData = e.allData
                    newData['birthday'] = data.birthday
                    newData['sex'] = data.sex
                    this.$refs.form.changeFormValue(newData)
                }
            }
        },
        submit(d) {
            let self = this

            if (d.UserGUID) {
                AjaxCommon('/api/User/EditUser', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        self.initPage(self.treeList)
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                d.Enable = '1'
                delete d.UserGUID
                // 根据类型调用不同接口
                let url = '/api/User/AddUser'
                AjaxCommon(url, 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        self.initPage(self.treeList)
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        dialogClose() {
            this.dialogShow = false
        },
        searchClick() {
            this.pageNo = 1
            this.initPage(this.treeList)
        },
        saveData() {
            if (this.selectUserList.length == 0) {
                PopupCommon.notify('info', '请至少选择一个用户')
                return
            }
            const title = this.oprType == '0' ? '核销' : '下发'
            if (this.dde == 0 && this.sde == 0) {
                PopupCommon.notify('info', '水定额和电定额的值加起来要大于0')
                return
            }
            const self = this
            // 核销
            PopupCommon.confirm(`电定额为：${this.dde}，水定额为：${this.sde}，是否进行${title}?`)
                .then(() => {
                    // api/QuotaAllot/DeducteAmount
                    AjaxCommon(`api/QuotaAllot/DeducteAmount`, 'post', {
                        //  账户GUID，多个用，分隔
                        ac_guids: self.selectUserList.map((t) => t.ac_guid).toString(),
                        /**
                         *  配发金额（如有多个需要|分隔） 如免费电金额、免费水金额  5|10或5|0
                         */
                        amount: `${self.dde}|${self.sde}`,
                        operType: self.oprType
                    }).then((res) => {
                        if (res?.data?.Code == 200) {
                            PopupCommon.notify('success', title + '成功')
                            self.initPage(self.treeList)
                        } else {
                            const msg = res?.data?.Message
                            if (msg) {
                                let errTitle = ''
                                if (typeof msg == 'object') {
                                    msg.map((t) => {
                                        errTitle += `${t.ac}：${t.msg}，`
                                    })
                                    errTitle = errTitle.substring(0, errTitle.length - 1)
                                } else {
                                    errTitle = msg
                                }
                                PopupCommon.notify('error', errTitle)
                            }
                        }
                    })
                })
                .catch(() => {
                    // 这里尽量写下，否则会报警告异常。
                    console.log('已取消删除')
                })
        },
        resetClick() {
            this.userName = ''
            this.dde = 0
            this.sde = 0
            this.pageNo = 1
            this.searchClick()
        },
        addClick() {
            // this.formConfig = userManageForm('add')
            // let formConfigItem = this.formConfig
            // formConfigItem.map((t) => {
            //     Object.keys(t).map((res) => {
            //         if (res == 'fieldName') {
            //             t.filedValue = ''
            //         }
            //     })
            // })
            // this.formConfig = formConfigItem
            this.type = 'add'
            // this.dialogTitle = '新增'
            // this.dialogShow = true
            this.showAdd = true
        },
        // 分页点击事件
        pageChange(p) {
            this.pageNo = p
            this.initPage(this.treeList)
        },
        deleteRow(d) {},
        editRow(d) {
            this.type = 'edit'
            this.showAdd = true
        },
        viewRow(d) {
            // this.acGuid = d.ac_guid
            // this.dialogTitle = `【${d.ac_name}】查看`
            // this.dialogShow = true
            this.showAdd = true
        },
        // 初始化事件
        initPage(list) {
            let self = this
            // let params = `/api/QuotaAllot/GetAcsQuotaScheme?PageSize=${this.pageSize}&PageIndex=${this.pageNo}`
            // if (list && list.length > 0) {
            //     this.spinShow = true
            //     params += `&buildIds=${list.map((t) => t.id)}`
            //     if (this.userName) {
            //         params += `&ac_name=${this.userName}`
            //     }
            //     AjaxCommon(params, 'get', null).then((res) => {
            //         if (res?.data?.Code == 200) {
            //             const data = res?.data.Message
            //             self.dataSource = data?.rows?.map((t) => {
            //                 if (t.ac_sum) {
            //                     t.ac_sum = parseFloat(t.ac_sum).toFixed(2)
            //                 }
            //                 return t
            //             })
            //             self.pageCount = parseInt(data?.total)
            //         } else {
            //             PopupCommon.notify('error', res?.data?.msg)
            //         }
            //         this.spinShow = false
            //     })
            // } else {
            let newData = []
            for (let index = 0; index < 10; index++) {
                let item = {
                    famc: '方案名称1' + index,
                    xiaji: '27',
                    dongji: '2',
                    zdkz: index % 2 == 0 ? '1,2' : '1',
                    xiajigaoyu: '27',
                    xiajidiyu: '22',
                    dongjigaoyu: '点水表混合',
                    dongjidiyu: '2',
                    sfyx: index % 2 == 0 ? 1 : 0,
                    sfkqsdkz: index % 2 == 0 ? 1 : 0,
                    zhczr: '张三' + index,
                    czsj: '2025-09-02 11:11:22',
                    bz: '备注1111111111' + index,
                    ktwd: '1231' + index
                }
                newData.push(item)
            }
            self.dataSource = newData
            self.selectUserList = []
            self.pageCount = 10
            // }
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }

        this.initPage()
    }
}
</script>

<style scoped lang="scss">
.demo-spin {
    background-color: rgba(0, 0, 0, 0.2);
}
.demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
    from {
        transform: rotate(0deg);
    }
    50% {
        transform: rotate(180deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
